package cn.jtool.dig.client.timer;

import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.SNGenerator;
import cn.jtool.dig.common.netty.TcpClient;
import io.netty.channel.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class TunnelHeartbeatSendTask {

    @Qualifier("tunnelClient")
    @Resource
    private TcpClient tunnelClient;

    public void run(){
        if(Objects.nonNull(this.tunnelClient) && this.tunnelClient.isRunning()){
            try{
                Channel channel = this.tunnelClient.getChannel();
                if(Objects.nonNull(channel) && channel.isActive()){
                    PacketHeader packetHeader = PacketHeader.builder()
                            .command(Commands.HEARBEAT.getCode())
                            .channelId(0x00L)
                            .digId(0x00)
                            .sn(SNGenerator.gen()).build();
                    channel.writeAndFlush(Packet.builder().header(packetHeader).build());
                }
            }catch (Exception e){
                log.error("获取隧道Channel异常",e);
            }
        }
    }

}
